#!/usr/bin/env python
# -*- coding:utf-8 -*-

# src/grujieclient/gruijieclientgtk.py

# Copyright (C) 2009 Gong Han <gong AT fedoraproject.org>

# This file is part of gRuijieClient.

# gRuijieClient is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published
# by the Free Software Foundation; version 3 only.

# gRuijieClient is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.

# You should have received a copy of the GNU General Public License
# along with gRuijieClient. If not, see <http://www.gnu.org/licenses/>.


import sys
import gobject
import gnome.ui
from globe import *
from systray import *
from ruijiecontrol import *
from ruijieconf import *

class gRuijieClientGTK:
    """
    RuijieClient front-end GTK main class
    @author: Gong Han
    """


    def __init__(self):

        # set hooks of email-agent and browser of aboutdialog
        gtk.about_dialog_set_email_hook(self.__url_hook, "mailto:")
        gtk.about_dialog_set_url_hook(self.__url_hook, "")
        # Set the Glade file and get main widgets
        self._wnd_aboutdialog = GladeUI.get_widget('wnd_aboutdialog')
        self._wnd_main = GladeUI.get_widget('wnd_main')
        self._btn_connect = GladeUI.get_widget('btn_connect')
        self._btn_disconnect = GladeUI.get_widget('btn_disconnect')
        self._item_connect = GladeUI.get_widget('menuitem_connect')
        self._item_disconnect = GladeUI.get_widget('menuitem_disconnect')
        self._textview_out = GladeUI.get_widget('textview_out')
        # start up system tray
        self._systray = SysTray(self._wnd_main)

        # Create our dictionary and connect it
        self._dic = {                    
            'on_btn_about_clicked' : self.on_btn_about_clicked,
            'ruijie_quit' : self.ruijie_quit,
            'on_wnd_main_delete_event': self.on_wnd_main_delete_event,
            'on_wnd_aboutdialog_close': self.on_wnd_aboutdialog_close,
            'on_btn_connect_clicked': self.on_btn_connect_clicked,
            'on_btn_disconnect_clicked': self.on_btn_disconnect_clicked,
            'on_button_saveset_clicked': self.on_button_saveset_clicked,
            'on_button_discardset_clicked': self.on_button_discardset_clicked
            }
        GladeUI.signal_autoconnect(self._dic)

        # install language
        gettext.bindtextdomain(RC_DOMAIN, LOCALE_DIR)
        gettext.textdomain(RC_DOMAIN)
        gettext.install(RC_DOMAIN, LOCALE_DIR, unicode=True)
        gtk.glade.bindtextdomain(RC_DOMAIN, LOCALE_DIR)
        gtk.glade.textdomain(RC_DOMAIN)

        # load configuration
        self._conf = RuijieConf('/etc/ruijie.conf')
        self._conf.load()
        # set text buf of textview
        self._textbuf = gtk.TextBuffer()
        self._textview_out.set_buffer(self._textbuf)
        # control instance to communicate with console
        self._control = RuijieClientControl('ruijieclient',
                                             self._textbuf,
                                             self._textview_out)
        # set a timer to auto connect in gtk main loop
        if self._conf.AutoConnect == '1':
            self._timer_id = gobject.timeout_add(100, self._auto_connect)

    def on_btn_about_clicked(self, widget=None):
        self._wnd_aboutdialog.run()

    def ruijie_quit(self, widget):
        # check connection status and then disconnect
        if self._control.get_status() > 3:
            self._control.disconnect()
        gtk.main_quit()

    def on_wnd_main_delete_event(self, widget, user_data):
        self._systray.on_icon_left_clicked()

    def on_wnd_aboutdialog_close(self, widget, user_data):
        self._wnd_aboutdialog.hide()

    def on_btn_connect_clicked(self, widget = None):
        if self._control.get_status() < 4:
            # change button status
            self._change_widgets(True)

            if self._control.connect():
                self._systray.set_tooltip('gRuijieClient - connected')
                if self._control.get_status() > 3:
                    self._systray.traynotify.put_msg('Server Message',
                                                     self._control.serv_msg)
                    # minimise to system tray
                    self._systray.on_icon_left_clicked()
            else:
                self._change_widgets(False)

    def on_btn_disconnect_clicked(self, widget = None):
        if self._control.get_status() > 2:
            # change button status
            self._change_widgets(False)

            if self._control.disconnect():
                self._systray.set_tooltip('gRuijieClient - unconnected')
            else:
                self._change_widgets(False)

    def on_button_saveset_clicked(self, widget):
        self._conf.save()

    def on_button_discardset_clicked(self, widget):
        self._conf.load()

    def _auto_connect(self):
        if self._timer_id is not None:
            gobject.source_remove(self._timer_id)
            self._timer_id = None
            self.on_btn_connect_clicked()
        return False
    
    # change widget status according to connection status
    def _change_widgets(self, preconnected):
        # if preconnected == True:
        self._item_connect.set_sensitive(not preconnected)
        self._btn_connect.set_sensitive(not preconnected)
        self._item_disconnect.set_sensitive(preconnected)
        self._btn_disconnect.set_sensitive(preconnected)

        # change trayicon
        if not preconnected:
            self._systray.set_from_file(GRUIJIECLIENT_IMAGE_DISCON)
        else:
            self._systray.set_from_file(GRUIJIECLIENT_IMAGE)

    def __url_hook(self, widget, url, scheme):
        gnome.ui.url_show_on_screen(scheme + url, widget.get_screen())

if __name__ == '__main__':
    print gRuijieClientGTK
